package com.yh.controller.admin;

import cn.hutool.core.date.DateUtil;
import com.yh.entity.*;
import com.yh.service.CinemaService;
import com.yh.service.MovieService;
import com.yh.utils.Constants;
import com.yh.vo.CustomPageAndNavigate;
import com.yh.vo.CinemaVO;
import com.yh.vo.HallVO;
import com.yh.vo.ResponseVO;
import com.yh.vo.ScheduleVO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.log4j.Logger;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yuhuan
 * @date 2022/01/13
 */
@RestController
@RequestMapping("/admin/cinema")
public class CinemaManageController {
    /**
     * 日志
     */
    private static final Logger logger = Logger.getLogger(CinemaManageController.class);

    @DubboReference(check = false)
    private CinemaService cinemaService;
    @DubboReference(check = false)
    private MovieService movieService;

    /**
     * 查询所有的影院品牌
     * 服务地址 http://localhost:8081/admin/cinema/brand/all
     */
    @RequestMapping("/brand/all")
    public ResponseVO findCinemaBrandAll() {
        List<Brand> brandList = cinemaService.findCinemaBrandAll();
        if (ObjectUtils.isEmpty(brandList)) {
            return ResponseVO.buildSuccessInstance(Constants.ResponseDataState.NULL_RESULT);
        }
        return ResponseVO.buildSuccessInstance(brandList);
    }

    /**
     * 查询所有的影院信息（从实体信息中拷贝的部分信息）
     * 服务地址 http://localhost:8081/admin/cinema/all
     */
    @RequestMapping("all")
    public ResponseVO findCinemaAll() {
        List<CinemaVO> voList = cinemaService.findCinemaAll();
        if (ObjectUtils.isEmpty(voList)) {
            return ResponseVO.buildSuccessInstance(Constants.ResponseDataState.NULL_RESULT);
        }
        return ResponseVO.buildSuccessInstance(voList);
    }

    /**
     * 查询所有的影院信息并分页（从实体信息中拷贝的部分信息）
     * 服务地址 http://localhost:8081/admin/cinema/all/page
     */
    @RequestMapping("/all/page")
    public ResponseVO findCinemaAllToPage(@RequestBody CinemaVO cinemaVO) {
        CustomPageAndNavigate page = cinemaService.findCinemaAllToPage(cinemaVO.getPageNum(), cinemaVO.getPageSize());
        return !ObjectUtils.isEmpty(page.getList()) ? ResponseVO.buildSuccessInstance(page) :
                ResponseVO.buildSuccessInstance(Constants.ResponseDataState.NULL_RESULT);
    }

    /**
     * 查询影院的详情信息（包括影院的基本信息、影院提供所有服务和影院播放的所有影片）
     * 服务地址 http://localhost:8081/admin/cinema/detail/id
     */
    @RequestMapping("/detail/id")
    public ResponseVO findCinemaDetailById(Integer cinemaId) {
        CinemaVO detail = cinemaService.findCinemaDetailById(cinemaId);
        if (ObjectUtils.isEmpty(detail)) {
            return ResponseVO.buildSuccessInstance(Constants.ResponseDataState.NULL_RESULT);
        }
        return ResponseVO.buildSuccessInstance(detail);
    }

    /**
     * 根据影片ID查询所有的影院信息
     * 服务地址 http:/localhost:8081/admin/cinema/by/movie
     */
    @RequestMapping("/by/movie")
    public ResponseVO findCinemaByMovieId(Integer movieId) {
        List<CinemaVO> voList = cinemaService.findCinemaByMovieId(movieId);
        if (ObjectUtils.isEmpty(voList)) {
            return ResponseVO.buildSuccessInstance(Constants.ResponseDataState.NULL_RESULT);
        }
        return ResponseVO.buildSuccessInstance(voList);
    }

    /**
     * 添加上映影片到影院；如果影片列表没有变化，说明没有新影片的加入，将直接响应null
     * 服务地址 http://localhost:8081/admin/cinema/add/movie/on/cinema
     */
    @RequestMapping("/add/movie/on/cinema")
    public ResponseVO addMovieOnCinemaDetail(@RequestBody CinemaVO vo) {
        int oldSize = vo.getMovies().size();
        List<Movie> movieList = cinemaService.addMovieOnCinemaDetail(vo);
        boolean success = movieList.size() != oldSize;
        if (success) {
            return ResponseVO.buildSuccessInstance(movieList);
        }
        return ResponseVO.buildSuccessInstance(Constants.ResponseDataState.NULL_RESULT);
    }

    /**
     * 移除影院已经上映的影片；不允许移除已经创建了放映计划（场次）的影片
     * 服务地址 http://localhost:8081/admin/cinema/del/movie/on/cinema
     */
    @RequestMapping("/del/movie/on/cinema")
    public ResponseVO deleteMovieOnCinemaDetail(@RequestBody CinemaVO vo) {
        List<Movie> movieList = cinemaService.deleteMovieOnCinemaDetail(vo);
        boolean isDel = movieList.size() != vo.getMovies().size();
        if (isDel) {
            return ResponseVO.buildSuccessInstance(movieList);
        }
        return ResponseVO.buildSuccessInstance(Constants.ResponseDataState.DATA_IS_OCCUPIED);
    }

    /**
     * 新增影院信息
     * 服务地址 http://localhost:8081/admin/cinema/add
     */
    @RequestMapping("add")
    public ResponseVO addCinema(@RequestBody CinemaVO vo) {
        int resp = cinemaService.addCinema(vo);
        if (resp > 0) {
            return ResponseVO.buildSuccessInstance(Constants.ResponseDataState.RESP_SUCCESS);
        }
        return ResponseVO.buildSuccessInstance(Constants.ResponseDataState.UPDATE_FAIL);
    }

    /**
     * 修改影院信息
     * 服务地址 http://localhost:8081/admin/cinema/update
     */
    @RequestMapping("update")
    public ResponseVO updateCinema(@RequestBody CinemaVO vo) {
        int resp = cinemaService.updateCinema(vo);
        if (resp > 0) {
            return ResponseVO.buildSuccessInstance(Constants.ResponseDataState.RESP_SUCCESS);
        }
        return ResponseVO.buildSuccessInstance(Constants.ResponseDataState.UPDATE_FAIL);
    }

    /**
     * 查询所有的影厅信息
     * 服务地址 http://localhost:8081/admin/cinema/hall/all
     */
    @RequestMapping("/hall/all")
    public ResponseVO findHallAll(@RequestBody CinemaVO cinemaVO) {
        CustomPageAndNavigate page = cinemaService.findHallAll(cinemaVO.getPageNum(), cinemaVO.getPageSize());
        return !ObjectUtils.isEmpty(page.getList()) ? ResponseVO.buildSuccessInstance(page) :
                ResponseVO.buildSuccessInstance(Constants.ResponseDataState.NULL_RESULT);
    }

    /**
     * 查询指定影院所有的影厅
     * 服务地址：http://localhost:8081/admin/cinema/hall/cinema/id
     */
    @RequestMapping("/hall/cinema/id")
    public ResponseVO findHallByCinemaId(Integer cinemaId) {
        List<Hall> hallByCinema = cinemaService.findHallByCinemaId(cinemaId);
        if (ObjectUtils.isEmpty(hallByCinema)) {
            return ResponseVO.buildSuccessInstance(Constants.ResponseDataState.NULL_RESULT);
        }
        return ResponseVO.buildSuccessInstance(hallByCinema);
    }

    /**
     * 根据ID查询影厅详情
     * 服务地址 http://localhost:8081/admin/cinema/hall/detail/id
     */
    @RequestMapping("/hall/detail/id")
    public ResponseVO findHallDetailById(Integer hallId) {
        HallVO hallDetailById = cinemaService.findHallDetailById(hallId);
        if (ObjectUtils.isEmpty(hallDetailById)) {
            return ResponseVO.buildSuccessInstance(Constants.ResponseDataState.NULL_RESULT);
        }
        // 初始化影厅的容量
        hallDetailById.examineHallCapacity();
        return ResponseVO.buildSuccessInstance(hallDetailById);
    }

    /**
     * 添加影厅信息
     * 服务地址 http://localhost:8081/admin/cinema/add/hall
     */
    @RequestMapping("/add/hall")
    public ResponseVO addHall(@RequestBody HallVO vo) {
        int result = cinemaService.addHall(vo);
        if (result > 0) {
            return ResponseVO.buildSuccessInstance(Constants.ResponseDataState.RESP_SUCCESS);
        }
        return ResponseVO.buildSuccessInstance(Constants.ResponseDataState.UPDATE_FAIL);
    }

    /**
     * 修改影厅信息
     * 服务地址 http://localhost:8081/admin/cinema/update/hall
     */
    @RequestMapping("/update/hall")
    public ResponseVO updateHall(@RequestBody HallVO vo) {
        int result = cinemaService.updateHall(vo);
        if (result > 0) {
            return ResponseVO.buildSuccessInstance(Constants.ResponseDataState.RESP_SUCCESS);
        }
        return ResponseVO.buildSuccessInstance(Constants.ResponseDataState.UPDATE_FAIL);
    }

    /**
     * 移除影厅的所有布局信息
     * 服务地址 http://localhost:8081/admin/cinema/del/layout
     */
    @RequestMapping("/del/layout")
    public ResponseVO removeLayoutByHallId(Integer hallId) {
        int result = cinemaService.removeLayoutByHallId(hallId);
        return ResponseVO.buildSuccessInstance(result);
    }

    /**
     * 查询所有的影厅类型
     * 服务地址：http://localhost:8081/admin/cinema/hall/type/all
     */
    @RequestMapping("/hall/type/all")
    public ResponseVO findHallTypeAll() {
        List<HallType> hallTypeList = cinemaService.findHallTypeAll();
        if (ObjectUtils.isEmpty(hallTypeList)) {
            return ResponseVO.buildSuccessInstance(Constants.ResponseDataState.NULL_RESULT);
        }
        return ResponseVO.buildSuccessInstance(hallTypeList);
    }

    /**
     * 查询所有的影厅放映计划(场次)
     * 服务地址 http://localhost:8081/admin/cinema/schedule/all
     */
    @RequestMapping("/schedule/all")
    public ResponseVO findScheduleAll(@RequestBody CinemaVO cinemaVO) {
        Integer pageNum = cinemaVO.getPageNum();
        Integer pageSize = cinemaVO.getPageSize();
        String searchCondition = cinemaVO.getSearchCondition();
        CustomPageAndNavigate page = cinemaService.findScheduleAll(pageNum, pageSize, searchCondition);
        return !ObjectUtils.isEmpty(page.getList()) ? ResponseVO.buildSuccessInstance(page) :
                ResponseVO.buildSuccessInstance(Constants.ResponseDataState.NULL_RESULT);
    }

    /**
     * 根据影片名字搜索日程
     * 服务地址 http://localhost:8081/admin/cinema/schedule/movie/name
     */
    @RequestMapping("/schedule/movie/name")
    public ResponseVO searchScheduleByMovieName(@RequestBody CinemaVO cinemaVO) {
        Integer pageNum = cinemaVO.getPageNum();
        Integer pageSize = cinemaVO.getPageSize();
        String keyword = cinemaVO.getKeyword();
        String searchCondition = cinemaVO.getSearchCondition();
        CustomPageAndNavigate page = null;
        if (ObjectUtils.isEmpty(keyword)) {
            page = cinemaService.findScheduleAll(pageNum, pageSize, searchCondition);
        } else {
            page = cinemaService.searchScheduleByMovieNameToPage(pageNum, pageSize, keyword, searchCondition);
        }
        if (ObjectUtils.isEmpty(page)) {
            return ResponseVO.buildSuccessInstance(Constants.ResponseDataState.NULL_RESULT);
        }
        return ResponseVO.buildSuccessInstance(page);
    }

    /**
     * 新增日程
     * 服务地址 http://localhost:8081/admin/cinema/add/schedule
     */
    @RequestMapping("/add/schedule")
    public ResponseVO addSchedule(@RequestBody ScheduleVO vo) {
        int resp = cinemaService.addSchedule(vo);
        return ResponseVO.buildSuccessInstance(resp);
    }

    /**
     * 取消放映计划
     * 服务地址 http://localhost:8081/admin/cinema/del/schedule
     */
    @RequestMapping("/del/schedule")
    public ResponseVO deleteSchedule(Integer scheduleId) {
        if (ObjectUtils.isEmpty(scheduleId)) {
            return ResponseVO.buildSuccessInstance(Constants.ResponseDataState.DELETE_FAIL);
        }
        boolean result = cinemaService.deleteSchedule(scheduleId);
        return result ? ResponseVO.buildSuccessInstance(Constants.ResponseDataState.RESP_SUCCESS)
                : ResponseVO.buildSuccessInstance(Constants.ResponseDataState.DATA_IS_OCCUPIED);
    }

    /**
     * 每日更新放映计划；更新规则是：找到所有的高分影片，并在同一天的同一个影院，有且仅在一个影厅的某一段
     * 时间生成一场放映计划；忽略已经被删除的影片
     * 服务地址：http://localhost:8081/admin/cinema/update/movie/show/time
     */
    @RequestMapping("/update/movie/show/time")
    public ResponseVO updateMovieShowTimeEveryDayTest() {
        List<Integer> movieIds = new ArrayList<>();
        // 找到所有的影片
        List<Movie> movies = movieService.findMovieAll();
        if (ObjectUtils.isEmpty(movies)) {
            return ResponseVO.buildSuccessInstance(Constants.ResponseDataState.NULL_RESULT);
        }
        // 生成高分影片的放映计划
        movies.forEach(movie -> {
            if (movie.getMovieScore() > Constants.MovieData.HIGH_SCORE_VIDEOS) {
                movieIds.add(movie.getMovieId());
            }
        });
        // 生成计划的日期
        String nowTime = DateUtil.today();
        cinemaService.updateScheduleByDateAndMovieId(movieIds, DateUtil.parse(nowTime));
        ResponseVO.InstanceBuild instanceBuild = new ResponseVO.InstanceBuild();
        return instanceBuild.setCode(200).setMsg("OK").build();
    }

    /**
     * 删除旧的影片放映计划（默认是超过30天的计划）
     * 服务地址：http://localhost:8081/admin/cinema/del/old/schedule
     */
    @RequestMapping("/del/old/schedule")
    public ResponseVO deleteOldSchedule() {
        int result = cinemaService.deleteOldSchedule();
        if (result > 0) {
            logger.debug(">>>>> 累计删除" + result + "条记录");
            return ResponseVO.buildSuccessInstance(Constants.ResponseDataState.RESP_SUCCESS, result);
        }
        return ResponseVO.buildSuccessInstance(Constants.ResponseDataState.NULL_RESULT);
    }
}
